package com.yiwei.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class YWCloudPlatformUtils {
    private Logger log = Logger.getLogger(YWCloudPlatformUtils.class.getName());
    private String baseUrl =  AssistantConfig.properties.getProperty("baseUrl");

    public String uploadFile(String urlStr, String token, File file) {
        String reStr = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(urlStr);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(60000).build();
            httppost.setConfig(requestConfig);
            httppost.addHeader("Authorization", "Bearer "+token);

            FileBody bin = new FileBody(file);
//            StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).build();
            httppost.setEntity(reqEntity);

            log.info("开始上传请求" + httppost.getRequestLine());
            log.info("上传使用token：" + AssistantConfig.properties.getProperty("token"));
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                log.info(String.valueOf(response.getStatusLine()));
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    reStr = EntityUtils.toString(response.getEntity());
                    log.info(reStr);
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return reStr;
    }

    public String uploadFileAndGetImgId(String token, File file){
        String reStr = uploadFile(baseUrl+"/imgs/upload", token, file);
        JSONObject jObj = new JSONObject(reStr);
        if (jObj.getInt("code") == 2000){
            String img_id = jObj.getJSONObject("content").getString("img_id");
            log.info(String.format("上传图片文件成功，图片ID是%s", img_id));
            return img_id;
        }
        log.warning("图像上传失败");
        return null;
    }
    
    public String getReadEdData(String urlStr, String token) {
        String reStr = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httppost = new HttpGet(urlStr);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(60000).build();
            httppost.setConfig(requestConfig);
            httppost.addHeader("Authorization", "Bearer "+token);
            log.info("使用token：" + AssistantConfig.properties.getProperty("token"));
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                log.info(String.valueOf(response.getStatusLine()));
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    reStr = EntityUtils.toString(response.getEntity());
                    log.info(reStr);
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return reStr;
    }
    
    /**
     * 获取 图片报告列表
     * 
     * @param urlStr
     * @param token
     * @return
     */
    public String getPicReportList(String urlStr, String token) {
        String reStr = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httppost = new HttpGet(urlStr);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(60000).build();
            httppost.setConfig(requestConfig);
            httppost.addHeader("Authorization", "Bearer "+token);
            log.info("使用token：" + AssistantConfig.properties.getProperty("token"));
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                log.info(String.valueOf(response.getStatusLine()));
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    reStr = EntityUtils.toString(response.getEntity());
                    log.info(reStr);
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return reStr;
    }

    public static final int cache = 10 * 1024;
	public static String download(String url, String filepath) {
		try {
			HttpClient client = HttpClients.createDefault();
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = client.execute(httpget);

			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();

			File file = new File(filepath);
			file.getParentFile().mkdirs();
			FileOutputStream fileout = new FileOutputStream(file);
			/**
			 * 根据实际运行效果 设置缓冲区大小
			 */
			byte[] buffer = new byte[cache];
			int ch = 0;
			while ((ch = is.read(buffer)) != -1) {
				fileout.write(buffer, 0, ch);
			}
			is.close();
			fileout.flush();
			fileout.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

    
    public static void main(String[] args){
    }

}
